package cn.edu.zime.tjh.iotapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.edu.zime.tjh.iotapp.adapter.DeviceAdapter;
import cn.edu.zime.tjh.iotapp.api.ApiCallback;
import cn.edu.zime.tjh.iotapp.api.ApiService;
import cn.edu.zime.tjh.iotapp.model.Device;

public class DeviceListActivity extends AppCompatActivity implements DeviceAdapter.OnDeviceClickListener {
    
    private static final String TAG = "DeviceListActivity";
    
    private RecyclerView recyclerDevices;
    private SwipeRefreshLayout swipeRefresh;
    private TextView textEmpty;
    private FloatingActionButton fabAddDevice;
    
    private DeviceAdapter deviceAdapter;
    private List<Device> deviceList;
    private ApiService apiService;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);
        
        // 初始化API服务
        apiService = ApiService.getInstance();
        
        // 初始化视图
        initViews();
        
        // 设置列表
        setupRecyclerView();
        
        // 设置下拉刷新
        swipeRefresh.setOnRefreshListener(this::loadDevices);
        
        // 设置添加设备按钮
        fabAddDevice.setOnClickListener(v -> showAddDeviceDialog());
        
        // 加载设备列表
        loadDevices();
    }
    
    private void initViews() {
        recyclerDevices = findViewById(R.id.recyclerDevices);
        swipeRefresh = findViewById(R.id.swipeRefresh);
        textEmpty = findViewById(R.id.textEmpty);
        fabAddDevice = findViewById(R.id.fabAddDevice);
        
        // 设置标题
        TextView titleText = findViewById(R.id.textTitle);
        if (titleText != null) {
            titleText.setText("设备管理");
        }
    }
    
    private void setupRecyclerView() {
        deviceList = new ArrayList<>();
        deviceAdapter = new DeviceAdapter(this, deviceList, this);
        
        recyclerDevices.setLayoutManager(new LinearLayoutManager(this));
        recyclerDevices.setAdapter(deviceAdapter);
    }
    
    private void loadDevices() {
        swipeRefresh.setRefreshing(true);
        
        apiService.getDeviceList(new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    // 检查响应状态码
                    if (response.has("data")) {
                        JSONArray deviceArray = response.getJSONArray("data");
                        List<Device> devices = new ArrayList<>();
                        
                        for (int i = 0; i < deviceArray.length(); i++) {
                            JSONObject deviceObj = deviceArray.getJSONObject(i);
                            
                            // 创建设备对象
                            Device device = new Device();
                            
                            // 设置必填字段
                            if (deviceObj.has("id") && !deviceObj.isNull("id")) {
                                device.setDevice_id(deviceObj.getString("id"));
                            } else if (deviceObj.has("device_id") && !deviceObj.isNull("device_id")) {
                                device.setDevice_id(deviceObj.getString("device_id"));
                            }
                            
                            if (deviceObj.has("name") && !deviceObj.isNull("name")) {
                                device.setDevice_name(deviceObj.getString("name"));
                            } else if (deviceObj.has("device_name") && !deviceObj.isNull("device_name")) {
                                device.setDevice_name(deviceObj.getString("device_name"));
                            }
                            
                            // 设置设备状态
                            if (deviceObj.has("status") && !deviceObj.isNull("status")) {
                                device.setDevice_status(deviceObj.getString("status"));
                            } else if (deviceObj.has("device_status") && !deviceObj.isNull("device_status")) {
                                device.setDevice_status(deviceObj.getString("device_status"));
                            } else {
                                device.setDevice_status("active"); // 默认为active
                            }
                            
                            // 设置其他可选字段
                            if (deviceObj.has("type") && !deviceObj.isNull("type")) {
                                device.setDevice_type(deviceObj.getString("type"));
                            } else if (deviceObj.has("device_type") && !deviceObj.isNull("device_type")) {
                                device.setDevice_type(deviceObj.getString("device_type"));
                            }
                            
                            // 只有在显式不为空的情况下才添加
                            if (device.getDevice_id() != null && device.getDevice_name() != null) {
                                devices.add(device);
                            }
                        }
                        
                        deviceList.clear();
                        deviceList.addAll(devices);
                        
                        runOnUiThread(() -> {
                            deviceAdapter.notifyDataSetChanged();
                            swipeRefresh.setRefreshing(false);
                            
                            // 更新空视图状态
                            if (deviceList.isEmpty()) {
                                textEmpty.setVisibility(View.VISIBLE);
                                recyclerDevices.setVisibility(View.GONE);
                            } else {
                                textEmpty.setVisibility(View.GONE);
                                recyclerDevices.setVisibility(View.VISIBLE);
                            }
                        });
                    } else {
                        String message = response.optString("message", "加载设备列表失败");
                        throw new Exception(message);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "解析设备列表失败: " + e.getMessage());
                    runOnUiThread(() -> {
                        Toast.makeText(DeviceListActivity.this, "加载设备列表失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        swipeRefresh.setRefreshing(false);
                    });
                }
            }
            
            @Override
            public void onFailure(String errorMsg) {
                Log.e(TAG, "加载设备列表失败: " + errorMsg);
                runOnUiThread(() -> {
                    Toast.makeText(DeviceListActivity.this, "加载设备列表失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }
        });
    }
    
    private void showAddDeviceDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_device, null);
        
        EditText editDeviceName = dialogView.findViewById(R.id.editDeviceName);
        Spinner spinnerDeviceTypes = dialogView.findViewById(R.id.spinnerDeviceTypes);
        
        // 设置设备类型下拉列表
        String[] deviceTypes = {"temperature", "humidity", "light", "camera", "gateway", "other"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, deviceTypes);
        spinnerDeviceTypes.setAdapter(adapter);
        
        AlertDialog dialog = new AlertDialog.Builder(this)
            .setView(dialogView)
            .setPositiveButton("添加", null) // 我们稍后会设置点击监听器
            .setNegativeButton("取消", null)
            .create();
        
        dialog.show(); // 先显示对话框
        
        // 设置确定按钮监听器，以便我们可以在关闭对话框之前验证输入
        dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> {
            String deviceName = editDeviceName.getText().toString().trim();
            String deviceType = spinnerDeviceTypes.getSelectedItem().toString();
            
            if (deviceName.isEmpty()) {
                editDeviceName.setError("请输入设备名称");
                return; // 不关闭对话框
            }
            
            // 关闭对话框并添加设备
            dialog.dismiss();
            addDevice(deviceName, deviceType);
        });
    }
    
    private void deleteDevice(String deviceId, int position) {
        apiService.deleteDevice(deviceId, new ApiCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                runOnUiThread(() -> {
                    // 删除成功，从列表中移除
                    deviceList.remove(position);
                    deviceAdapter.notifyItemRemoved(position);
                    deviceAdapter.notifyItemRangeChanged(position, deviceList.size());
                    
                    // 检查列表是否为空
                    if (deviceList.isEmpty()) {
                        textEmpty.setVisibility(View.VISIBLE);
                        recyclerDevices.setVisibility(View.GONE);
                    }
                    
                    Toast.makeText(DeviceListActivity.this, "设备已删除", Toast.LENGTH_SHORT).show();
                });
            }
            
            @Override
            public void onFailure(String errorMsg) {
                runOnUiThread(() -> {
                    Toast.makeText(DeviceListActivity.this, "删除设备失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    @Override
    public void onDeviceClick(Device device) {
        // 跳转到设备详情页面
        Intent intent = new Intent(this, DeviceDetailActivity.class);
        intent.putExtra("device_id", device.getDevice_id());
        startActivity(intent);
    }
    
    @Override
    public void onDeviceLongClick(Device device, int position) {
        // 显示删除确认对话框
        new AlertDialog.Builder(this)
            .setTitle("删除设备")
            .setMessage("确定要删除设备 " + device.getDevice_name() + " 吗？")
            .setPositiveButton("删除", (dialog, which) -> {
                deleteDevice(device.getDevice_id(), position);
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    public void back(View view) {
        finish();
    }
    
    private void addDevice(String deviceName, String deviceType) {
        // 调用API添加设备
        apiService.addDevice(
            deviceName,
            deviceType, 
            "", // device_info 
            "",  // device_web
            "",  // image
            new ApiCallback() {
                @Override
                public void onSuccess(JSONObject response) {
                    try {
                        JSONObject data = response.getJSONObject("data");
                        String deviceId = data.getString("id");
                        
                        // 创建新设备对象并添加到列表
                        Device newDevice = new Device();
                        newDevice.setDevice_id(deviceId);
                        newDevice.setDevice_name(deviceName);
                        newDevice.setDevice_type(deviceType);
                        newDevice.setDevice_status("active");
                        
                        // 添加到列表顶部
                        deviceList.add(0, newDevice);
                        
                        runOnUiThread(() -> {
                            deviceAdapter.notifyItemInserted(0);
                            recyclerDevices.scrollToPosition(0);
                            
                            // 确保列表可见
                            if (deviceList.size() == 1) {
                                textEmpty.setVisibility(View.GONE);
                                recyclerDevices.setVisibility(View.VISIBLE);
                            }
                            
                            Toast.makeText(DeviceListActivity.this, "设备添加成功", Toast.LENGTH_SHORT).show();
                        });
                    } catch (Exception e) {
                        Log.e(TAG, "处理设备添加响应失败: " + e.getMessage());
                        runOnUiThread(() -> {
                            Toast.makeText(DeviceListActivity.this, "添加设备失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        });
                    }
                }
                
                @Override
                public void onFailure(String errorMsg) {
                    Log.e(TAG, "添加设备请求失败: " + errorMsg);
                    runOnUiThread(() -> {
                        Toast.makeText(DeviceListActivity.this, "添加设备失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                    });
                }
            }
        );
    }
} 